package com.order.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version 1.0
 * @author: yu.tan
 * @date: 2020/11/7 22:49
 * @Description: 自定义异常返回页面
 */
@Component
public class ExceptionHandlerPage implements UrlBlockHandler {


    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {

        /**
         * BlockException 异常接口，包含Sentinel的五个异常
         * FlowException    限流异常
         * AuthorityException   授权异常
         * DegradeException 降级异常
         * ParamFlowException 参数限流异常
         * SystemBlockException 系统负载异常
         */
        httpServletResponse.setContentType("application/json;charset=utf-8");
        ResponseData responseData=null;

        if (e instanceof FlowException) {
            responseData=  new ResponseData(-1, "接口被限流了！");
        } else if (e instanceof DegradeException) {
            responseData=new ResponseData(-2, "接口被降级了！");
        } else if (e instanceof AuthorityException) {
            responseData=new ResponseData(-3, "授权异常！");
        } else if (e instanceof SystemBlockException) {
            responseData=new ResponseData(-4, "系统负载异常！");
        } else if (e instanceof ParamFlowException) {
            responseData=new ResponseData(-5, "参数限流异常！");
        }

        httpServletResponse.getWriter().write(JSON.toJSONString(responseData));
    }


}

@Data
@AllArgsConstructor
@NoArgsConstructor
class ResponseData {
    private int code;
    private String message;
}